package com.zhuxulin.xiaomi.net;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

public class Request {

	private Method method;
	private String path;
	private HashMap<String, String> params;

	public Request(Method method, String path) {
		this.method = method;
		this.path = path;
		params = new HashMap<String, String>();
	}

	public Method getMethod() {
		return method;
	}

	public void setMethod(Method method) {
		this.method = method;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public HttpEntity getEntity() {
		List<BasicNameValuePair> pair = new ArrayList<BasicNameValuePair>();
		for (String key : params.keySet()) {
			pair.add(new BasicNameValuePair(key, params.get(key)));
		}
		try {
			return new UrlEncodedFormEntity(pair, "utf-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public String getQueryString() {
		StringBuffer qs = new StringBuffer("?");
		for (String key : params.keySet()) {
			qs.append(key + "=" + params.get(key) + "&");
		}
		qs.deleteCharAt(qs.length() - 1);
		return qs.toString();
	}

	public void putParam(String key, String value) {
		params.put(key, value);
	}

	public void setParams(HashMap<String, String> params) {
		this.params = params;
	}

	public void removeParam(String key) {
		params.remove(key);
	}

	@Override
	public String toString() {
		return String.format("%s %s", method.toString(), path);
	}

}
